package com.aiton.bamin.bamindaijiadrier.activity;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.anim.listAnim;
import com.aiton.administrator.shane_library.shane.app.SysApplication;
import com.aiton.administrator.shane_library.shane.upgrade.UpgradeUtils;
import com.aiton.administrator.shane_library.shane.utils.ACache;
import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.utils.HTTPUtils;
import com.aiton.administrator.shane_library.shane.utils.UILUtils;
import com.aiton.administrator.shane_library.shane.utils.VolleyListener;
import com.aiton.administrator.shane_library.shane.widget.SingleBtnDialog;
import com.aiton.administrator.shane_library.shane.widget.TwoBtnDialog;
import com.aiton.bamin.bamindaijiadrier.R;
import com.aiton.bamin.bamindaijiadrier.TTSController;
import com.aiton.bamin.bamindaijiadrier.constant.Constant;
import com.aiton.bamin.bamindaijiadrier.model.Order;
import com.aiton.bamin.bamindaijiadrier.model.SendOrder;
import com.aiton.bamin.bamindaijiadrier.model.User;
import com.aiton.bamin.bamindaijiadrier.model.VersionAndHouTaiIsCanUse;
import com.aiton.bamin.bamindaijiadrier.server.LocationService;
import com.android.volley.VolleyError;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;

import static com.aiton.bamin.bamindaijiadrier.server.LocationService.mLocationLatLng;


public class MainActivity extends ZjbBaseActivity implements View.OnClickListener {
    private boolean isShouFaChe = false;
    private DrawerLayout drawer_layout;
    private LinearLayout list_left_drawer;
    private List<SendOrder> mSendOrderList = new ArrayList<>();
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMyBind = (LocationService.MyBind) service;
            //检查服务器是否存活和当前版本是否可用
            isShouFaChe = mMyBind.isShouFaChe();
            Log.e("onServiceConnected ", "onServiceConnected 服务收发车" + isShouFaChe);
            checkVersionAndHouTaiIsCanUse();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    private TextView mTextView_shoufache;
    private String mId;
    private String mDeviceId;
    private ImageView mImageView_shoufache;
    private List<SendOrder> mMainSendOrderList = new ArrayList<>();
    private List<Boolean> mIsFinishList = new ArrayList<>();
    private int mMainSendOrderListPosition = 0;

    private BroadcastReceiver recevier = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case Constant.BROADCASTCODE.STOP_GET_ORDER:
                    stopGetOrder();
                    break;
                case Constant.BROADCASTCODE.SEND_ORDER_SERVER:
                    SendOrder sendOrder = (SendOrder) intent.getSerializableExtra(Constant.INTENT_KEY.AUTO_CANCLE_ORDER);
                    boolean contains = isContains(sendOrder);
                    if (!contains) {
                        mSendOrderList.add(sendOrder);
                        mMainSendOrderList.add(sendOrder);
                        mOrderAdapter.notifyDataSetChanged();
                        mIsFinishList.add(false);
                        CountDownTimer countDownTimer = new CountDownTimer(60000*2, 1) {
                            public void onTick(long millisUntilFinished) {
                                if (millisUntilFinished>0&&millisUntilFinished<100&&mIsFinishList.size()!=0) {
                                    Log.e("onTick ", "onTick mMainSendOrderListPosition"+mMainSendOrderListPosition);
                                    mIsFinishList.set(mMainSendOrderListPosition, true);
                                }
                            }

                            public void onFinish() {
                                Log.e("onFinish ", "onFinish倒计时 进来");
                                mMainSendOrderListPosition = mMainSendOrderListPosition + 1;
                                mSendOrderList.clear();
                                for (int i = 0; i < mIsFinishList.size(); i++) {
                                    Log.e("onFinish ", "onFinish倒计时 mIsFinishList"+mIsFinishList.get(i));
                                    if (!mIsFinishList.get(i)) {
                                        mSendOrderList.add(mMainSendOrderList.get(i));
                                    }
                                }
                                mOrderAdapter.notifyDataSetChanged();
                                clearOrder();
                            }
                        };
                        countDownTimer.start();
                    }
                    break;
                case Constant.BROADCASTCODE.USER:
                    User mUser = (User) intent.getSerializableExtra(Constant.INTENT_KEY.USER);
                    setUserName(mUser.getDatas().getName());
                    loadAvatarImg(mUser.getDatas().getImage());
                    break;
                case Constant.BROADCASTCODE.PAY_SUCCESS:
                    String sendOrderValue = intent.getStringExtra(Constant.INTENT_KEY.PAY_SUCCESS);
                    Log.e("ComfirmCostActivity", "sendOrderValue: --->>" + sendOrderValue);
                    SendOrder mSendOrder = GsonUtils.parseJSON(sendOrderValue, SendOrder.class);
                    if (mSendOrder != null) {
                        Log.e("ComfirmCostActivity", "handleMessage: --paySuccess->>" + mSendOrder.getOrderStatus());
                        if (mSendOrder.getAppOrderStatus() == Constant.ORDER_STATUS.NO_EVALUATION) {
                            Toast.makeText(MainActivity.this, "订单号为"+mSendOrder.getId()+"的订单已支付", Toast.LENGTH_SHORT).show();
//                        mRela_wait_pay.setVisibility(View.GONE);
//                        mRela_success_pay.setVisibility(View.VISIBLE);
                        }
                    }
                    break;

            }
        }
    };
    private TextView mTv_time;
    private double currentTime;
    private TextView mTv_orderSum;

    private void clearOrder() {
        if (mSendOrderList.size()==0){
            mMainSendOrderListPosition=0;
            mMainSendOrderList.clear();
            mIsFinishList.clear();
        }
    }

    private ImageView mImg_orderIng;
    private Order mOrder;

    private boolean isContains(SendOrder sendOrder) {
        for (int i = 0; i < mSendOrderList.size(); i++) {
            if (mSendOrderList.get(i).getOrderId().equals(sendOrder.getOrderId())) {
                return true;
            }
        }
        return false;
    }

    private ListView mListView_getorder;
    private MyAdapter mOrderAdapter;
    private String name;
    private TTSController ttsManager;
    private TextView mTextView_phone_head;
    private User mUser;
    private ImageView mImg_Avatar;
    private ImageView mImg_mine;
    private boolean unfinishedOrder;
    private LocationService.MyBind mMyBind;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//保持屏幕常亮
        //语音引擎初始化
        ttsManager = TTSController.getInstance(this);
        ttsManager.init();
        ttsManager.startSpeaking();
        init();
        initGPS();
    }

    /**
     * 判断GPS模块是否开启，如果没有则开启提示
     */
    private void initGPS() {
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        //
        if (!locationManager
                .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "为了定位准确，请打开GPS",
                    Toast.LENGTH_SHORT).show();

            final TwoBtnDialog twoBtnDialog = new TwoBtnDialog(this, "为了定位准确，请打开GPS", "确定", "取消");
            twoBtnDialog.setClicklistener(new TwoBtnDialog.ClickListenerInterface() {
                @Override
                public void doConfirm() {
                    // 转到手机设置界面，用户设置GPS
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, 0); // 设置完成后返回到原来的界面
                    twoBtnDialog.dismiss();
                }

                @Override
                public void doCancel() {
                    twoBtnDialog.dismiss();
                }
            });
            twoBtnDialog.show();
        }
    }

    private void toast(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 检查服务器是否存活和当前版本是否可用
     */
    private void checkVersionAndHouTaiIsCanUse() {
        String url = Constant.Url.CHECK_LIVE;
        Map<String, String> map = new HashMap<>();
        HTTPUtils.post(MainActivity.this, url, map, new VolleyListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                setDialogCkeck("服务器正在升级，暂停服务", "确认");
            }

            @Override
            public void onResponse(String s) {
                Log.e("onResponse ", "检查当前版本是否可用" + s);
                try {
                    VersionAndHouTaiIsCanUse versionAndHouTaiIsCanUse = GsonUtils.parseJSON(s, VersionAndHouTaiIsCanUse.class);
                    if (versionAndHouTaiIsCanUse.getStatus() == 0) {
                        int ableVersion = versionAndHouTaiIsCanUse.getDatas().getAbleVersion();
                        if (versionAndHouTaiIsCanUse.getDatas().isLive()) {
                            if (Constant.ABLEVERSION < ableVersion) {
                                setDialogCkeckAble("当前版本不可用，请更新到最新版本", "确认");
                            } else {
                                checkUpGrade();
                                //检查是否在其他设备上登录
                                checkIsLoginOnOtherDevice();
                            }
                        } else {
                            setDialogCkeck(versionAndHouTaiIsCanUse.getDatas().getMessage(), "确认");
                        }
                    } else {
                        setDialogCkeck(versionAndHouTaiIsCanUse.getMes(), "确认");
                    }
                } catch (Exception e) {
                    toast("服务器出错");
                }
            }
        });
    }

    /**
     * 检查是否在其他设备上登录
     */
    private void checkIsLoginOnOtherDevice() {
        Log.e("nOtherDevice", "设备号" + mDeviceId + "用户号" + mId);
        if (!"".equals(mDeviceId)) {
            String url = Constant.Url.LOADLOGINID;
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            params.put("account_id", mId + "");
            asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    String s = new String(responseBody);
                    Log.e("onResponse ", "检查是否在其他设备上登录" + s);

                    try {
                        User user = GsonUtils.parseJSON(s, User.class);
                        if (user.getStatus() == 0) {
                            if (!(user.getDatas().getDeviceid()).equals(mDeviceId)) {
                                cancelLoadingDialog();
                                setDialog("你的账号登录异常\n请重新登录", "确定");
                            } else {
                                getOrderIsIng(false);
                            }
                        }else{
                            cancelLoadingDialog();
                            setDialog("系统出错，请重新登录", "确定");

                        }
                    } catch (Exception e) {
                        toast("解析出错");
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    cancelLoadingDialog();
                    setDialog("获取信息出错", "确定");
                    Log.e("onErrorResponse ", "获取唯一设备号失败");
                }
            });
        }
    }

    /**
     * 检查是否有正在进行的订单
     */
    private void getOrderIsIng(final boolean faChe) {
        Log.e("getOrderIsIng ", "进去检查请求");
        showLoadingDialog();
        String url = Constant.Url.DRIVER_FIND_NOT_FINISH_ORDER;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("driverId", mId);
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                Log.e("onSuccess ", "检查是否有订单正在进行：" + s);
                try {
                    if ("true".equals(s)) {

                        unfinishedOrder = true;
                        cancelLoadingDialog();
                        mImg_orderIng.setVisibility(View.VISIBLE);
                        final TwoBtnDialog twoBtnDialog = new TwoBtnDialog(MainActivity.this, "你有未完成的订单", "继续", "取消");
                        twoBtnDialog.setClicklistener(new TwoBtnDialog.ClickListenerInterface() {
                            @Override
                            public void doConfirm() {
                                twoBtnDialog.dismiss();
                                stopGetOrder();
                                Intent intent = new Intent();

                                intent.setClass(MainActivity.this, OrderIngActivity.class);
                                startActivityTo(intent);


                            }

                            @Override
                            public void doCancel() {
                                twoBtnDialog.dismiss();
                            }
                        });

                        twoBtnDialog.show();
                    } else {
                        cancelLoadingDialog();
                        mImg_orderIng.setVisibility(View.GONE);
                        if (isShouFaChe || faChe) {
                            Log.e("onSuccess ", "没有进行");
                            Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate);
                            LinearInterpolator lin = new LinearInterpolator();
                            animation.setInterpolator(lin);
                            if (faChe) {
                                ttsManager.startSpeaking();
                                ttsManager.playText("八闽出行，风雨同行！");
                            }
                            mTextView_shoufache.setText("停止");
                            mImageView_shoufache.setImageResource(R.mipmap.circle_jiedan);
                            if (animation != null) {
                                mImageView_shoufache.startAnimation(animation);
                            }
                            isShouFaChe = true;
                            mMyBind.startGetOrder();
                            unfinishedOrder = false;
                        }
                    }
                } catch (Exception e) {
                    Log.e("onSuccess ", "检查出错");
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Log.e("onFailure ", "检查请求失败");
            }
        });
    }



    /**
     * 弹出未登录按钮跳转登录界面并清除登录信息
     *
     * @param messageTxt
     * @param iSeeTxt
     */
    private void setDialog(String messageTxt, String iSeeTxt) {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, messageTxt, iSeeTxt);
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();
                //清除用户登录信息
                ACache aCache = ACache.get(MainActivity.this);
                aCache.clear();
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivityTo(intent);
            }
        });
        singleBtnDialog.show();
    }

    private void checkUpGrade() {
        UpgradeUtils.checkUpgrade(MainActivity.this, Constant.Url.UP_GRADE);
    }

    private void setDialogCkeckAble(String messageTxt, String iSeeTxt) {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, messageTxt, iSeeTxt);
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();
                UpgradeUtils.checkUpgradeIsAble(MainActivity.this, Constant.Url.UP_GRADE);

            }
        });
        singleBtnDialog.show();
    }

    //dialog提示
    private void setDialogCkeck(String messageTxt, String iSeeTxt) {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, messageTxt, iSeeTxt);
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();
                SysApplication.getInstance().exit();

            }
        });
        singleBtnDialog.show();
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void initViews() {
        showLoadingDialog();
        mOrderAdapter = new MyAdapter();
        mListView_getorder.setAdapter(mOrderAdapter);

        if (mUser != null) {
            setUserName(mUser.getDatas().getName());
            loadAvatarImg(mUser.getDatas().getImage());
            Log.e("MainActivity", "onResume: --->>");
        }

        mImg_orderIng.setImageResource(R.drawable.order_ing);
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日 EEEE");
        String format = simpleDateFormat.format(date);
        mTv_time.setText(format);


    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageView_mine).setOnClickListener(this);
        findViewById(R.id.rela_mine).setOnClickListener(this);
        findViewById(R.id.rela_setting).setOnClickListener(this);
        findViewById(R.id.rela_shoufache).setOnClickListener(this);
        mImg_Avatar.setOnClickListener(this);
        findViewById(R.id.image_adDialog).setOnClickListener(this);
        findViewById(R.id.rela_all_order).setOnClickListener(this);
        findViewById(R.id.rela_kefu).setOnClickListener(this);
        findViewById(R.id.rela_wallet).setOnClickListener(this);
        findViewById(R.id.rela_message).setOnClickListener(this);
        mImg_orderIng.setOnClickListener(this);
    }

    @Override
    protected void initSP() {
        ACache aCache = ACache.get(MainActivity.this);
        mUser = (User) aCache.getAsObject(Constant.ACACHE.USER);

        if (mUser != null) {
            mId = "" + mUser.getDatas().getId();
            name = mUser.getDatas().getName();
            mDeviceId = mUser.getDatas().getDeviceid();
            Log.e("MainActivity", "imgUrl: --->>" + mUser.getDatas().getImage());
            Log.e("MainActivity", "用户ID: --->>" + mId);
            Log.e("MainActivity", "设备号: --->>" + mDeviceId);
        }
    }

    @Override
    protected void initIntent() {

    }
    @Override
    protected void findID() {
        drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
        list_left_drawer = (LinearLayout) findViewById(R.id.list_left_drawer);
        mTextView_shoufache = (TextView) findViewById(R.id.textView_shoufache);
        mImageView_shoufache = (ImageView) findViewById(R.id.imageView_shoufache);
        mListView_getorder = (ListView) findViewById(R.id.listView_getorder);
        mTextView_phone_head = (TextView) findViewById(R.id.textView_phone_head);
        mImg_Avatar = (ImageView) findViewById(R.id.imageView_touXiang);
        mImg_mine = (ImageView) findViewById(R.id.imageView_mine);
        mImg_orderIng = (ImageView) findViewById(R.id.img_orderIng);
        mTv_time = (TextView) findViewById(R.id.tv_time);
//        mTv_orderSum = (TextView) findViewById(R.id.tv_orderSum);

    }

    class MyAdapter extends BaseAdapter {

        class ViewHolder {
            TextView textView_start;
            TextView textView_end;
            TextView textView_HowLong;
            TextView textView_cost;
        }

        @Override
        public int getCount() {
            return mSendOrderList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.get_order_item_single, null);
                holder.textView_start = (TextView) convertView.findViewById(R.id.textView_start);
                holder.textView_end = (TextView) convertView.findViewById(R.id.textView_end);
                holder.textView_HowLong = (TextView) convertView.findViewById(R.id.textView_HowLong);
                holder.textView_cost = (TextView) convertView.findViewById(R.id.textView_cost);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (mSendOrderList.size() > 0) {
                final SendOrder sendOrder = mSendOrderList.get(position);
                convertView.findViewById(R.id.line_order_item).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        orderInfoDialog orderInfoDialog = new orderInfoDialog(MainActivity.this, position);
                        orderInfoDialog.show();
                    }
                });

                final View finalConvertView = convertView;
                convertView.findViewById(R.id.img_close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteCell(finalConvertView, position);

                    }
                });
                holder.textView_start.setText(sendOrder.getStartLocation());
                holder.textView_end.setText(sendOrder.getEndLocation());
                holder.textView_HowLong.setText(sendOrder.getMileage() + "公里");
                holder.textView_cost.setText(sendOrder.getMoney() + "");
                listAnim.showItemAnim(convertView,position);
            }
            return convertView;
        }
    }

    private void deleteCell(final View v, final int index) {
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.item_remove);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                for (int i = 0; i < mMainSendOrderList.size(); i++) {

                    if (mMainSendOrderList.get(i).getId()==mSendOrderList.get(index).getId()){
                        mIsFinishList.set(i,true);
                    }
                }
                mSendOrderList.remove(index);
                mOrderAdapter.notifyDataSetChanged();

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        v.startAnimation(animation);
    }

    class orderInfoDialog extends Dialog {
        private Context context;
        private int position;

        public orderInfoDialog(Context context, int position) {
            super(context, com.aiton.administrator.shane_library.R.style.dialog);
            this.context = context;
            this.position = position;
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            View inflate = LayoutInflater.from(MainActivity.this).inflate(R.layout.get_order_item, null);
            setContentView(inflate);
            final SendOrder sendOrder = mSendOrderList.get(position);

            TextView textView_start = (TextView) inflate.findViewById(R.id.textView_start);
            TextView textView_end = (TextView) inflate.findViewById(R.id.textView_end);
            TextView textView_HowLong = (TextView) inflate.findViewById(R.id.textView_HowLong);
            TextView textView_cost = (TextView) inflate.findViewById(R.id.textView_cost);
            TextView textView_fee = (TextView) inflate.findViewById(R.id.textView_fee);

            textView_start.setText(sendOrder.getStartLocation());
            textView_end.setText(sendOrder.getEndLocation());
            textView_HowLong.setText(sendOrder.getMileage() + "公里");
            textView_cost.setText(sendOrder.getMoney() + "");
            textView_fee.setText(sendOrder.getFee() + "");

            inflate.findViewById(R.id.button_ignore).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
            inflate.findViewById(R.id.button_accept).setOnClickListener(new View.OnClickListener() {
                long lastClick = 0;

                @Override
                public void onClick(View v) {

                    //大于一秒方个通过
                    if (System.currentTimeMillis() - lastClick <= 1000) {
                        return;
                    }
                    lastClick = System.currentTimeMillis();
                    aceptOrder(position);
                    dismiss();
                }
            });

            Window dialogWindow = getWindow();
            dialogWindow.setWindowAnimations(R.style.dialogOrderAnim);
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            DisplayMetrics d = context.getResources().getDisplayMetrics(); // 获取屏幕宽、高用
            lp.width = (int) (d.widthPixels * 0.9); // 高度设置为屏幕的0.6
            dialogWindow.setAttributes(lp);
        }
    }

    /**
     * 司机接单
     *
     * @param position
     */
    private void aceptOrder(final int position) {
        String url = Constant.Url.ACECPT_ORDER;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        SendOrder sendOrder = mSendOrderList.get(position);
        params.put("orderId", sendOrder.getOrderId());
        params.put("driverId", mId);
        params.put("driverPhone", mUser.getDatas().getPhone());
        params.put("driverName", name);
        params.put("driverCoordinate", mLocationLatLng.longitude + "," + mLocationLatLng.latitude);
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                try {
                    Log.e("onSuccess ", "接受订单返回值" + s);
                    Order order = GsonUtils.parseJSON(s, Order.class);
                    int status = order.getStatus();
                    ttsManager.stopSpeaking();
                    ttsManager.startSpeaking();
                    if (status == 0) {
                        stopGetOrder();
                        ttsManager.playText("抢单成功!");
                        mSendOrderList.clear();
                        mOrderAdapter.notifyDataSetChanged();
                        Intent intent = new Intent();
                        intent.putExtra(Constant.INTENT_KEY.ORDER_ING, order);
                        intent.setClass(MainActivity.this, OrderIngActivity.class);
                        startActivityTo(intent);
                    } else if (status == 1) {
                        ttsManager.playText("抢单失败!");
                        toast("抢单失败");
                        mSendOrderList.remove(position);
                        mOrderAdapter.notifyDataSetChanged();
                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        unbindService(conn);
    }

    @Override
    protected void onDestroy() {
        Log.e("onDestroy ", "onDestroy ");
        super.onDestroy();
        unregisterReceiver(recevier);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
//        mMapView.onResume();
        ACache aCache = ACache.get(MainActivity.this);
        mUser = (User) aCache.getAsObject(Constant.ACACHE.USER);

        if (mUser != null) {
            mId = "" + mUser.getDatas().getId();
            name = mUser.getDatas().getName();
            mDeviceId = mUser.getDatas().getDeviceid();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.image_adDialog:
                startActivityTo(intent.setClass(this, MessageActivity.class));
                break;
            case R.id.img_orderIng:
//                loadUnfishOrder();
                intent.setClass(MainActivity.this, OrderIngActivity.class);
                startActivityTo(intent);
                break;
            case R.id.rela_message://消息
                startActivityTo(intent.setClass(this, MessageActivity.class));
                break;
            case R.id.rela_setting://更多，设置
                intent.setClass(MainActivity.this, SettingActivity.class);
                startActivityTo(intent);
                drawer_layout.closeDrawer(list_left_drawer);
                break;
            case R.id.imageView_mine:
                drawer_layout.openDrawer(list_left_drawer);
                break;
            case R.id.rela_shoufache://接单
                if (isShouFaChe) {
                    ttsManager.stopSpeaking();
                    ttsManager.startSpeaking();
                    ttsManager.playText("停止接单了！");
                    stopGetOrder();
                } else {
                    getOrderIsIng(true);
                }
                break;
            case R.id.imageView_touXiang://跳转个人信息
                intent.setClass(this, MineActivity.class);
                startActivityForResultTo(intent, Constant.REQUEST_RESULT_CODE.USER_INFO);
                drawer_layout.closeDrawer(list_left_drawer);
                break;
            case R.id.rela_all_order://所有订单
                intent.setClass(this, AllOrderActivity.class);
                intent.putExtra(Constant.INTENT_KEY.USER_ID, mUser.getDatas().getId());
                intent.putExtra(Constant.INTENT_KEY.UNFINISHED_ORDER, unfinishedOrder);
                Log.e("MainActivity", "用户ID: --->>" + mUser.getDatas().getId());
                startActivityForResultTo(intent, Constant.REQUEST_RESULT_CODE.USER_ID);
                drawer_layout.closeDrawer(list_left_drawer);
                break;
            case R.id.rela_kefu://客服
                intent.setClass(this, KefuActivity.class);
                startActivityTo(intent);
                drawer_layout.closeDrawer(list_left_drawer);
                break;
            case R.id.rela_wallet://钱包
                intent.setClass(this, WalletActivity.class);
                intent.putExtra(Constant.INTENT_KEY.USER,mUser);
                startActivityTo(intent);
                drawer_layout.closeDrawer(list_left_drawer);
                break;
        }
    }

    private void stopGetOrder() {

        isShouFaChe = false;
        mSendOrderList.clear();
        mOrderAdapter.notifyDataSetChanged();
        mTextView_shoufache.setText("接单");
        mImageView_shoufache.setImageResource(R.mipmap.circle);
        mImageView_shoufache.clearAnimation();
        mMyBind.clearLocation();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_RESULT_CODE.USER_INFO && resultCode == Constant.REQUEST_RESULT_CODE.USER_INFO) {
            //用户信息
            String userName = data.getStringExtra(Constant.INTENT_KEY.USER_NAME);
            String userAvatar = data.getStringExtra(Constant.INTENT_KEY.USER_AVATAR);
            setUserName(userName);
            loadAvatarImg(userAvatar);
        }

    }

    /**
     * 设置用户姓名
     *
     * @param name
     */
    private void setUserName(String name) {
        if (name != null && !TextUtils.isEmpty(name)) {
            mTextView_phone_head.setText(name);
        } else {
            mTextView_phone_head.setText(mUser.getDatas().getPhone());
        }
    }

    /**
     * 加载头像
     *
     * @param mImage
     */
    private void loadAvatarImg(String mImage) {
        if (mImage != null && !TextUtils.isEmpty(mImage)) {
            ImageLoader.getInstance().clearDiskCache();
            Log.e("checkLogin", "图片URL" + mImage);
            UILUtils.displayImageNoAnim(mImage, mImg_Avatar);
            UILUtils.displayImageNoAnim(mImage, mImg_mine);
        } else {
            mImg_Avatar.setImageResource(R.mipmap.ic_avatar);
            mImg_mine.setImageResource(R.mipmap.ic_avatar);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.e("onStart ", "onStart 绑服务");
        Intent server = new Intent();
        server.setClass(MainActivity.this, LocationService.class);
        bindService(server, conn, Context.BIND_AUTO_CREATE);
        startService(server);

        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.BROADCASTCODE.SEND_ORDER_SERVER);
        filter.addAction(Constant.BROADCASTCODE.USER);
        filter.addAction(Constant.BROADCASTCODE.STOP_GET_ORDER);
        filter.addAction(Constant.BROADCASTCODE.PAY_SUCCESS);
        registerReceiver(recevier, filter);
    }

    @Override
    public void onBackPressed() {
        if (isShouFaChe){
            TwoBtnDialog twoBtnDialog = new TwoBtnDialog(this,"退出后是否继续接单","确定","取消");
            twoBtnDialog.setClicklistener(new TwoBtnDialog.ClickListenerInterface() {
                @Override
                public void doConfirm() {
                    finishTo();

                }

                @Override
                public void doCancel() {
                    mMyBind.clearLocation();
                    finishTo();
                }
            });
            twoBtnDialog.show();

        }else{
            if (System.currentTimeMillis() - currentTime > 1000) {
                Toast toast = Toast.makeText(MainActivity.this, "双击退出应用", Toast.LENGTH_SHORT);
                toast.show();
                currentTime = System.currentTimeMillis();
            } else {
                finishTo();
            }
        }
    }

}
